<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .box {
        height: 5000px;
        background-color: rgb(161, 205, 223);
    }
</style>

<body>
    <div class="box"></div>
    <script>
        // 单位时间执行一次
        function callback() {
            console.log('节流触发了');
        }

        // 高阶函数 返回值或参数也是函数 高阶函数天生就是闭包
        function throttle(cb, delay) {
            let isScrolling, last //定时器 上一次执行
            return function(args) {
                let that = this; //当前作用域
                let _args = arguments; //函数执行时有的所有参数
                let now = +new Date();
                // console.log(now, 'now');
                // console.log(last, 'last');
                if (last && now < last + delay) {
                    clearTimeout(isScrolling);
                    isScrolling = setTimeout(() => {
                        last = now
                        cb.apply(that, _args);
                    }, delay)
                } else {
                    last = now
                    cb.apply(that, _args) //先执行一次
                }

            }
        }

        window.addEventListener('scroll', throttle(callback, 1000))
    </script>
</body>

</html>